package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.config.LocationContext;
import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.*;
import cn.com.ejiakanghu.form.AddGoodsForm;
import cn.com.ejiakanghu.vo.SubOrderGoodsVo;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.core.util.InventoryUtil;
import org.linlinjava.litemall.db.config.WxPayScoreConfig;
import org.linlinjava.litemall.db.dao.AgedmallChargeTemplateLeasePeriodMapper;
import org.linlinjava.litemall.db.dao.AgedmallGoodsOnlineServiceMapper;
import org.linlinjava.litemall.db.dao.AgedmallVipLevelMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.domain.AgedmallGoodsOnlineService;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.app.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.com.ejiakanghu.core.utils.WxResponseCode.GOODS_NO_STOCK;
import static cn.com.ejiakanghu.core.utils.WxResponseCode.GOODS_UNSHELVE;


/**
 * @author houzb
 * @Description
 * @create 2021-04-05 23:49
 */
@Service
public class CartManager {

    private Logger logger = LoggerFactory.getLogger(CartManager.class);
    @Autowired
    private LitemallCartService cartService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private LitemallAddressService addressService;
    @Autowired
    private CouponVerifyService couponVerifyService;
    @Autowired
    private LitemallGrouponRulesService grouponRulesService;
    @Autowired
    private LitemallCouponUserService couponUserService;
    @Autowired
    private GoodsManager goodsManager;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private AgedmallGoodsServiceService agedmallGoodsServiceService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private AgedmallOrderSerialService agedmallOrderSerialService;
    @Autowired
    private AgedmallStoreService agedmallStoreService;
    @Autowired
    private AgedmallGoodsShipTypeService agedmallGoodsShipTypeService;
    @Autowired
    private AgedmallStoreGoodsService agedmallStoreGoodsService;
    @Autowired
    private AgedmallChargeTemplateService agedmallChargeTemplateService;
    @Autowired
    private AgedmallUserInfoService agedmallUserInfoService;
    @Autowired
    private AgedmallGoodsSpecificationInfoService agedmallGoodsSpecificationInfoService;
    @Autowired
    private AgedmallHospitalSendService agedmallHospitalSendService;
    @Autowired
    private AgedmallGoodsPartsService agedmallGoodsPartsService;
    @Autowired
    private AgedmallOnlinesService agedmallOnlinesService;
    @Autowired
    private LitemallGoodsProductService litemallGoodsProductService;
    @Resource
    private AgedmallGoodsOnlineServiceMapper agedmallGoodsOnlineServiceMapper;
    @Resource
    private AgedmallVipLevelMapper agedmallVipLevelMapper;
    @Resource
    private LitemallUserMapper litemallUserMapper;

    @Resource
    private AgedmallChargeTemplateLeasePeriodMapper agedmallChargeTemplateLeasePeriodMapper;

    public BaseResult index(Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        List<LitemallCart> list = cartService.queryByUid(userId);
        List<LitemallCart> cartList = new ArrayList<>();
        // TODO
        // 如果系统检查商品已删除或已下架，则系统自动删除。
        // 更好的效果应该是告知用户商品失效，允许用户点击按钮来清除失效商品。
        for (LitemallCart cart : list) {
            LitemallGoods goods = goodsService.findById(cart.getGoodsId());
            if (goods == null || !goods.getIsOnSale()) {
                cartService.deleteById(cart.getId());
                logger.debug("系统自动删除失效购物车商品 goodsId=" + cart.getGoodsId() + " productId=" + cart.getProductId());
            } else {
                cartList.add(cart);
            }
        }

        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (LitemallCart cart : cartList) {
            goodsCount += cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            if (cart.getChecked()) {
                checkedGoodsCount += cart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);

        Map<String, Object> result = new HashMap<>();
        result.put("cartList", cartList);
        result.put("cartTotal", cartTotal);

        return RespUtil.success(result);
    }

    public BaseResult add(Integer userId, LitemallCart cart) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        if (cart == null) {
            return RespUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return RespUtil.badArgument();
        }
        if (number <= 0) {
            return RespUtil.badArgument();
        }

        //判断商品是否可以购买
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return RespUtil.fail(GOODS_UNSHELVE, "商品已下架");
        }

        LitemallGoodsProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
        if (existCart == null) {
            //取得规格的信息,判断规格库存
            if (product == null || number > product.getNumber()) {
                return RespUtil.fail(GOODS_NO_STOCK, "库存不足");
            }

            cart.setId(null);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            if (StringUtils.isEmpty(product.getUrl())) {
                cart.setPicUrl(goods.getPicUrl());
            } else {
                cart.setPicUrl(product.getUrl());
            }
            cart.setPrice(product.getPrice());
            cart.setSpecifications(product.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        } else {
            //取得规格的信息,判断规格库存
            int num = existCart.getNumber() + number;
            if (num > product.getNumber()) {
                return RespUtil.fail(GOODS_NO_STOCK, "库存不足");
            }
            existCart.setNumber((short) num);
            if (cartService.updateById(existCart) == 0) {
                return RespUtil.updatedDataFailed();
            }
        }

        return goodscount(userId);
    }

    public BaseResult goodscount(Integer userId) {
        if (userId == null) {
            return RespUtil.success(0);
        }

        int goodsCount = 0;
        List<LitemallCart> cartList = cartService.queryByUid(userId);
        for (LitemallCart cart : cartList) {
            goodsCount += cart.getNumber();
        }

        return RespUtil.success(goodsCount);
    }


    /**
     * 立即购买
     */
    public BaseResult fastadd(Integer userId, LitemallCart cart) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        if (cart == null) {
            return RespUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return RespUtil.badArgument();
        }
        if (number <= 0) {
            return RespUtil.badArgument();
        }

        //判断商品是否可以购买
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return RespUtil.fail(GOODS_UNSHELVE, "商品已下架");
        }

        LitemallGoodsProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
        if (existCart == null) {
            //取得规格的信息,判断规格库存
            if (product == null || number > product.getNumber()) {
                return RespUtil.fail(GOODS_NO_STOCK, "库存不足");
            }

            cart.setId(null);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            if (StringUtils.isEmpty(product.getUrl())) {
                cart.setPicUrl(goods.getPicUrl());
            } else {
                cart.setPicUrl(product.getUrl());
            }
            cart.setPrice(product.getPrice());
            cart.setSpecifications(product.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        } else {
            //取得规格的信息,判断规格库存
            int num = number;
            if (num > product.getNumber()) {
                return RespUtil.fail(GOODS_NO_STOCK, "库存不足");
            }
            existCart.setNumber((short) num);
            if (cartService.updateById(existCart) == 0) {
                return RespUtil.updatedDataFailed();
            }
        }

        return RespUtil.success(existCart != null ? existCart.getId() : cart.getId());
    }

    /**
     * 更新购物车数量
     *
     * @param userId
     * @param cart
     * @return
     */
    public BaseResult update(Integer userId, LitemallCart cart) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        Integer id = cart.getId();
        if (!ObjectUtils.allNotNull(id, productId, number, goodsId)) {
            return RespUtil.badArgument();
        }
        if (number <= 0) {
            return RespUtil.badArgument();
        }

        //判断是否存在该订单
        // 如果不存在，直接返回错误
        LitemallCart existCart = cartService.findById(userId, id);
        if (existCart == null) {
            return RespUtil.badArgumentValue();
        }

        // 判断goodsId和productId是否与当前cart里的值一致
        if (!existCart.getGoodsId().equals(goodsId)) {
            return RespUtil.badArgumentValue();
        }
        if (!existCart.getProductId().equals(productId)) {
            return RespUtil.badArgumentValue();
        }

        //判断商品是否可以购买
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return RespUtil.fail(GOODS_UNSHELVE, "商品已下架");
        }

        //取得规格的信息,判断规格库存
        LitemallGoodsProduct product = productService.findById(productId);
        if (product == null || product.getNumber() < number) {
            return RespUtil.fail(GOODS_UNSHELVE, "库存不足");
        }

        existCart.setNumber(number.shortValue());
        if (cartService.updateById(existCart) == 0) {
            return RespUtil.updatedDataFailed();
        }
        return RespUtil.success();
    }

    /**
     * 选中
     *
     * @param userId
     * @return
     */
    public BaseResult checked(Integer userId, List<Integer> productIds, Integer checkValue) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        if (productIds == null) {
            return RespUtil.badArgument();
        }

        if (checkValue == null) {
            return RespUtil.badArgument();
        }
        Boolean isChecked = (checkValue == 1);

        cartService.updateCheck(userId, productIds, isChecked);
        return index(userId);
    }

    /**
     * 删除
     *
     * @param userId
     * @param productIds
     * @return
     */
    public BaseResult delete(Integer userId, List<Integer> productIds) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        if (productIds == null || productIds.size() == 0) {
            return RespUtil.badArgument();
        }

        cartService.delete(productIds, userId);
        return index(userId);
    }


    public BaseResult checkout(Integer userId, Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        // 收货地址
        LitemallAddress checkedAddress = null;
        if (addressId == null || addressId.equals(0)) {
            checkedAddress = addressService.findDefault(userId);
            // 如果仍然没有地址，则是没有收货地址
            // 返回一个空的地址id=0，这样前端则会提醒添加地址
            if (checkedAddress == null) {
                checkedAddress = new LitemallAddress();
                checkedAddress.setId(0);
                addressId = 0;
            } else {
                addressId = checkedAddress.getId();
            }

        } else {
            checkedAddress = addressService.query(userId, addressId);
            // 如果null, 则报错
            if (checkedAddress == null) {
                return RespUtil.badArgumentValue();
            }
        }

        // 团购优惠
        BigDecimal grouponPrice = new BigDecimal(0.00);
        LitemallGrouponRules grouponRules = grouponRulesService.findById(grouponRulesId);
        if (grouponRules != null) {
            grouponPrice = grouponRules.getDiscount();
        }

        // 商品价格
        List<LitemallCart> checkedGoodsList = null;
        if (cartId == null || cartId.equals(0)) {
            checkedGoodsList = cartService.queryByUidAndChecked(userId);
        } else {
            LitemallCart cart = cartService.findById(userId, cartId);
            if (cart == null) {
                return RespUtil.badArgumentValue();
            }
            checkedGoodsList = new ArrayList<>(1);
            checkedGoodsList.add(cart);
        }
        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        for (LitemallCart cart : checkedGoodsList) {
            //  只有当团购规格商品ID符合才进行团购优惠
            if (grouponRules != null && grouponRules.getGoodsId().equals(cart.getGoodsId())) {
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().subtract(grouponPrice).multiply(new BigDecimal(cart.getNumber())));
            } else {
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }

        // 计算优惠券可用情况
        BigDecimal tmpCouponPrice = new BigDecimal(0.00);
        Integer tmpCouponId = 0;
        Integer tmpUserCouponId = 0;
        int tmpCouponLength = 0;
        List<LitemallCouponUser> couponUserList = couponUserService.queryAll(userId);
        for (LitemallCouponUser couponUser : couponUserList) {
            LitemallCoupon coupon = couponVerifyService.checkCoupon(userId, couponUser.getCouponId(), couponUser.getId(), checkedGoodsPrice, checkedGoodsList);
            if (coupon == null) {
                continue;
            }

            tmpCouponLength++;
            if (tmpCouponPrice.compareTo(coupon.getDiscount()) == -1) {
                tmpCouponPrice = coupon.getDiscount();
                tmpCouponId = coupon.getId();
                tmpUserCouponId = couponUser.getId();
            }
        }
        // 获取优惠券减免金额，优惠券可用数量
        int availableCouponLength = tmpCouponLength;
        BigDecimal couponPrice = new BigDecimal(0);
        // 这里存在三种情况
        // 1. 用户不想使用优惠券，则不处理
        // 2. 用户想自动使用优惠券，则选择合适优惠券
        // 3. 用户已选择优惠券，则测试优惠券是否合适
        if (couponId == null || couponId.equals(-1)) {
            couponId = -1;
            userCouponId = -1;
        } else if (couponId.equals(0)) {
            couponPrice = tmpCouponPrice;
            couponId = tmpCouponId;
            userCouponId = tmpUserCouponId;
        } else {
            LitemallCoupon coupon = couponVerifyService.checkCoupon(userId, couponId, userCouponId, checkedGoodsPrice, checkedGoodsList);
            // 用户选择的优惠券有问题，则选择合适优惠券，否则使用用户选择的优惠券
            if (coupon == null) {
                couponPrice = tmpCouponPrice;
                couponId = tmpCouponId;
                userCouponId = tmpUserCouponId;
            } else {
                couponPrice = coupon.getDiscount();
            }
        }

        // 根据订单商品总价计算运费，满88则免运费，否则8元；
        BigDecimal freightPrice = new BigDecimal(0.00);
        if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
            freightPrice = SystemConfig.getFreight();
        }

        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0.00);

        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0.00));

        BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);

        Map<String, Object> data = new HashMap<>();
        data.put("addressId", addressId);
        data.put("couponId", couponId);
        data.put("userCouponId", userCouponId);
        data.put("cartId", cartId);
        data.put("grouponRulesId", grouponRulesId);
        data.put("grouponPrice", grouponPrice);
        data.put("checkedAddress", checkedAddress);
        data.put("availableCouponLength", availableCouponLength);
        data.put("goodsTotalPrice", checkedGoodsPrice);
        data.put("freightPrice", freightPrice);
        data.put("couponPrice", couponPrice);
        data.put("orderTotalPrice", orderTotalPrice);
        data.put("actualPrice", actualPrice);
        data.put("checkedGoodsList", checkedGoodsList);
        return RespUtil.success(data);
    }

    @Transactional
    public BaseResult addGoods(Integer userId, AddGoodsForm addGoodsForm) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        // 分组id
        String goodsGroupId = getGroupId(addGoodsForm);
        // 根据分组id查找 已有数据 更新数量，没有数据 新增
        List<LitemallCart> cartList = cartService.getByGoodsGroupId(userId, goodsGroupId);
        if (CollectionUtils.isNotEmpty(cartList)) {
            // 更新主商品
            SelectGoodsSkuInfo mainGoods = addGoodsForm.getMainGoods();
            updateGoods(cartList, mainGoods.getGoodsSpec(), CartConstant.GOODS_TYPE_MAIN);
            // 更新推荐商品
            List<SelectGoodsSkuInfo> fitGoodsList = addGoodsForm.getFitGoodsList();
            if (CollectionUtils.isNotEmpty(fitGoodsList)) {
                fitGoodsList.forEach(p -> updateGoods(cartList, p.getGoodsSpec(), CartConstant.GOODS_TYPE_FIT));
            }
            // 更新组合商品
            List<SelectGoodsSkuInfo> packGoodsList = addGoodsForm.getPackGoodsList();
            if (CollectionUtils.isNotEmpty(packGoodsList)) {
                packGoodsList.forEach(p -> updateGoods(cartList, p.getGoodsSpec(), CartConstant.GOODS_TYPE_PACK));
            }
        } else {
            Integer saleUserId = addGoodsForm.getSaleUserId();
            Integer hospitalId = addGoodsForm.getHospitalId();
            Integer isSub = addGoodsForm.getIsSub();
            Integer channel = addGoodsForm.getChannel();
            String hosLinkCode = addGoodsForm.getHosLinkCode();
            // 保存主商品
            SelectGoodsSkuInfo mainGoods = addGoodsForm.getMainGoods();
            saveGoods(userId, mainGoods, goodsGroupId, saleUserId, hospitalId, isSub, CartConstant.GOODS_TYPE_MAIN,channel,hosLinkCode);
            // 保存推荐商品
            List<SelectGoodsSkuInfo> fitGoodsList = addGoodsForm.getFitGoodsList();
            if (CollectionUtils.isNotEmpty(fitGoodsList)) {
                fitGoodsList.forEach(p -> saveGoods(userId, p, goodsGroupId, saleUserId, hospitalId, isSub, CartConstant.GOODS_TYPE_FIT,channel,hosLinkCode));
            }
            // 保存组合商品
            List<SelectGoodsSkuInfo> packGoodsList = addGoodsForm.getPackGoodsList();
            if (CollectionUtils.isNotEmpty(packGoodsList)) {
                packGoodsList.forEach(p -> saveGoods(userId, p, goodsGroupId, saleUserId, hospitalId, isSub, CartConstant.GOODS_TYPE_PACK,channel,hosLinkCode));
            }
        }
        return RespUtil.success();
    }

    private String getGroupId(AddGoodsForm addGoodsForm) {
        //分组id md5(医院id + 主商品id+推荐商品id正序+组合商品id正序)
        StringBuffer ids = new StringBuffer();
        if (null != addGoodsForm.getHospitalId()) {
            ids.append(addGoodsForm.getHospitalId());
            if (null != addGoodsForm.getIsSub()) {
                ids.append(addGoodsForm.getIsSub());
            }
        }
        // 主商品
        SelectGoodsSkuInfo mainGoods = addGoodsForm.getMainGoods();
        ids.append(getMd5Ids(mainGoods));
        // 推荐商品
        List<SelectGoodsSkuInfo> fitGoodsList = addGoodsForm.getFitGoodsList();
        if (CollectionUtils.isNotEmpty(fitGoodsList)) {
            fitGoodsList.sort(Comparator.comparing(o -> o.getGoodsSpec().getSkuId()));
            fitGoodsList.forEach(p -> ids.append(getMd5Ids(p)));
        }
        // 组合商品
        List<SelectGoodsSkuInfo> packGoodsList = addGoodsForm.getPackGoodsList();
        if (CollectionUtils.isNotEmpty(packGoodsList)) {
            packGoodsList.sort(Comparator.comparing(o -> o.getGoodsSpec().getSkuId()));
            packGoodsList.forEach(p -> ids.append(getMd5Ids(p)));
        }
        System.out.println(ids.toString());
        String groupId = DigestUtils.md5Hex(ids.toString());
        return groupId;
    }

    private StringBuffer getMd5Ids(SelectGoodsSkuInfo selectGoodsSkuInfo) {
        StringBuffer ids = new StringBuffer();
        // 商品SKU
        GoodsSpecInfo goodsSpecInfo = selectGoodsSkuInfo.getGoodsSpec();
        ids.append(goodsSpecInfo.getSkuId());
        // 定制服务SKU
        List<CustomSpecInfo> customSpec = selectGoodsSkuInfo.getCustomSpec();
        if (CollectionUtils.isNotEmpty(customSpec)) {
            customSpec.sort(Comparator.comparing(o -> o.getId()));
            customSpec.forEach(p -> {
                List<String> selectids = p.getSelected().stream().map(q -> q.getSkuId()).sorted().collect(Collectors.toList());
                selectids.forEach(q -> ids.append(q));
            });
        }

        //在线服务 SKU
        List<CustomSpecInfo> serviceSpec = selectGoodsSkuInfo.getServiceSpec();
        if (CollectionUtils.isNotEmpty(serviceSpec)){
            serviceSpec.sort(Comparator.comparing(o -> o.getId()));
            serviceSpec.forEach(p -> {
                List<String> selectids = p.getSelected().stream().map(q -> q.getSkuId()).sorted().collect(Collectors.toList());
                selectids.forEach(q -> ids.append(q));
            });

        }

        // 特色服务SKU
        List<ExtendSpecInfo> extendSpec = selectGoodsSkuInfo.getExtendSpec();
        if (CollectionUtils.isNotEmpty(extendSpec)) {
            extendSpec.sort(Comparator.comparing(o -> o.getId()));
            extendSpec.forEach(p -> {
                List<String> selectids = Arrays.stream(p.getSelected().split(",")).sorted().collect(Collectors.toList());
                selectids.forEach(q -> ids.append(q));
            });
        }
        return ids;
    }

    private void saveGoods(Integer userId, SelectGoodsSkuInfo selectGoodsSkuInfo, String goodsGroupId,
                           Integer saleUserId, Integer hospitalId, Integer isSub, String goodsType,Integer channel,String hosLinkCode) {
        LitemallCart litemallCart = new LitemallCart();
        litemallCart.setSaleUserId(null == saleUserId ? null : saleUserId+"");
        litemallCart.setGoodsType(goodsType);
        // 商品SKU
        GoodsSpecInfo goodsSpecInfo = selectGoodsSkuInfo.getGoodsSpec();
        StoreGoodsVo storeGoods = agedmallStoreGoodsService.getStoreGoodsById(goodsSpecInfo.getId());
//        LitemallGoods goods = goodsService.findById(storeGoods.getId());
//        LitemallGoodsProduct product = productService.findById(Integer.parseInt(goodsSpecInfo.getSkuId()));
        int stockNum = orderManager.getByStoreGoods(storeGoods, Integer.parseInt(goodsSpecInfo.getSkuId()));
        if (goodsSpecInfo.getStock() > stockNum) {
            throw new BizException("库存不足");
        }
        StoreGoodsProductVo product = agedmallStoreGoodsService.getStoreGoodsProduct(storeGoods.getStoreId(), storeGoods.getId(), Integer.parseInt(goodsSpecInfo.getSkuId()));
        litemallCart.setUserId(userId);
        litemallCart.setGoodsId(goodsSpecInfo.getId());
        litemallCart.setGoodsSn(storeGoods.getGoodsSn());
        litemallCart.setGoodsName(storeGoods.getName());
        litemallCart.setProductId(Integer.parseInt(goodsSpecInfo.getSkuId()));
        boolean flag = GoodsConstant.GOODS_TYPE_LEASE.equals(storeGoods.getGoodsType());
        litemallCart.setPrice(flag ? product.getLeaseDeposit() : product.getSaleRetailPrice());
        litemallCart.setNumber(goodsSpecInfo.getStock().shortValue());
        litemallCart.setSpecifications(product.getSpecifications());
        litemallCart.setChecked(true);
        litemallCart.setPicUrl(product.getUrl());
        litemallCart.setGoodsGroupId(goodsGroupId);
        litemallCart.setHospitalId(hospitalId);
        litemallCart.setIsSub(isSub);
        litemallCart.setChannel(channel);
        litemallCart.setHosLinkCode(hosLinkCode);
        litemallCart.setRuleId(selectGoodsSkuInfo.getGoodsSpec().getRuleId());
        // 定制服务SKU
        List<CustomSpecInfo> customSpec = selectGoodsSkuInfo.getCustomSpec();
        litemallCart.setPartIds(JSONObject.toJSONString(customSpec));
        // 定制在线服务SKU
        List<CustomSpecInfo> serviceSpec = selectGoodsSkuInfo.getServiceSpec();
        litemallCart.setOnlineServiceIds(JSONObject.toJSONString(serviceSpec));
        // 特色服务SKU
        List<ExtendSpecInfo> extendSpec = selectGoodsSkuInfo.getExtendSpec();
        litemallCart.setServiceIds(JSONObject.toJSONString(extendSpec));

        cartService.add(litemallCart);
    }

    private void updateGoods(List<LitemallCart> cartList, GoodsSpecInfo goodsSpecInfo, String goodsType) {
        LitemallCart cart = cartList.stream().filter(p ->
                p.getGoodsId().equals(goodsSpecInfo.getId()) && goodsType.equals(p.getGoodsType())
        ).findFirst().orElse(null);
        if (null != cart) {
            StoreGoodsVo storeGoods = agedmallStoreGoodsService.getStoreGoodsById(goodsSpecInfo.getId());
//            LitemallGoods goods = goodsService.findById(storeGoods.getId());
            // 租赁商品数量固定为1 购物车数量不加
            if (GoodsConstant.GOODS_TYPE_LEASE.equals(storeGoods.getGoodsType())) {
                return;
            }
//            LitemallGoodsProduct product = productService.findById(Integer.parseInt(goodsSpecInfo.getSkuId()));
            int stockNum = orderManager.getByStoreGoods(storeGoods, Integer.parseInt(goodsSpecInfo.getSkuId()));
            int total = cart.getNumber() + goodsSpecInfo.getStock();
            if (total > stockNum) {
                throw new BizException("库存不足");
            }
            cart.setNumber((short)total);
            cartService.updateById(cart);
        }
    }

    public BaseResult removeBatch(Integer userId, String groupIds) {
        List<String> goodsGroupIdList = Arrays.stream(groupIds.split(",")).collect(Collectors.toList());
        cartService.removeByGoodsGroupIdList(userId, goodsGroupIdList);
        return RespUtil.success();
    }

    public BaseResult cartList(Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        Map<String, Object> data = new HashMap<>();

        // 查询所有购物车商品
        List<LitemallCart> cartList = cartService.queryWithBlobByUid(userId);

        data.put("cartGroupList", groupCart(cartList));
        return RespUtil.success(data);
    }

    public BaseResult hospitalCartList(Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> hospitalList = new ArrayList<>();

        // 查询所有购物车商品
        List<LitemallCart> cartList = cartService.queryHospWithBlobByUid(userId);
        // 按医院分租
        Map<Integer, List<LitemallCart>> hospMap = cartList.stream().collect(Collectors.toMap(
                LitemallCart::getHospitalId,
                p -> {
                    List<LitemallCart> carts = new ArrayList<>();
                    carts.add(p);
                    return carts;
                },
                (list1, list2) -> {
                    list1.addAll(list2);
                    return list1;
                }
        ));
        for (Map.Entry<Integer, List<LitemallCart>> integerListEntry : hospMap.entrySet()) {
            AgedmallHospitalSend agedmallHospitalSend = agedmallHospitalSendService.getById(integerListEntry.getKey());
            GoodsHospitalInfo hospitalInfo = new GoodsHospitalInfo(agedmallHospitalSend);

            Map<String, Object> hospital = new HashMap<>();
            hospital.put("hospitalInfo", hospitalInfo);
            hospital.put("cartGroupList", groupCart(integerListEntry.getValue()));
            hospitalList.add(hospital);
        }

        data.put("hospitalList", hospitalList);
        return RespUtil.success(data);
    }

    private List<Map> groupCart(List<LitemallCart> cartList) {
        List<Map> cartGroupList = new ArrayList<>();

        // 按分组id 分组
        Map<String, List<LitemallCart>> groupMap = cartList.stream().collect(Collectors.toMap(
                LitemallCart::getGoodsGroupId,
                p -> {
                    List<LitemallCart> carts = new ArrayList<>();
                    carts.add(p);
                    return carts;
                },
                (list1, list2) -> {
                    list1.addAll(list2);
                    return list1;
                }
        ));
        // 组装返回
        groupMap.forEach((k, l) -> {
            Map<String, Object> item = new HashMap<>();
            item.put("id", k);
            // 总价
            BigDecimal totalPrice = BigDecimal.ZERO;
            // 主商品
            LitemallCart mainCart = l.stream().filter(p -> CartConstant.GOODS_TYPE_MAIN.equals(p.getGoodsType())).findFirst().orElse(null);
            if (null != mainCart) {
                Map<String, Object> map = getGoodsInfo(mainCart);
                if(ObjectUtil.isNotNull(map.get("totalPrice"))){
                    item.put("mainGoods", map);
                    totalPrice = totalPrice.add((BigDecimal) map.get("totalPrice"));
                }
            }
            // 推荐商品
            List<LitemallCart> fitCarts = l.stream().filter(p -> CartConstant.GOODS_TYPE_FIT.equals(p.getGoodsType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(fitCarts)) {
                List<Map<String, Object>> list = new ArrayList<>();
                fitCarts.forEach(p -> {
                    Map<String, Object> map = getGoodsInfo(p);
                    list.add(map);
                });
                item.put("fitGoods", list);

                totalPrice = totalPrice.add(list.stream().map(p -> (BigDecimal) p.get("totalPrice")).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
            // 组合商品
            List<LitemallCart> packCarts = l.stream().filter(p -> CartConstant.GOODS_TYPE_PACK.equals(p.getGoodsType())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(packCarts)) {
                List<Map<String, Object>> list = new ArrayList<>();
                packCarts.forEach(p -> {
                    Map<String, Object> map = getGoodsInfo(p);
                    list.add(map);
                });
                item.put("packGoods", list);

                totalPrice = totalPrice.add(list.stream().map(p -> (BigDecimal) p.get("totalPrice")).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
            item.put("totalPrice", totalPrice.doubleValue());
            cartGroupList.add(item);
        });

        return cartGroupList;
    }

    private Map<String, Object> getGoodsInfo(LitemallCart cart) {
        Map<String, Object> map = new HashMap<>();

        StoreGoodsVo goods = agedmallStoreGoodsService.getStoreGoodsById(cart.getGoodsId());
        StoreGoodsProductVo goodsProduct = agedmallStoreGoodsService.getStoreGoodsProduct(goods.getStoreId(), goods.getId(), cart.getProductId());
        if(goodsProduct==null){
            return map;
        }
        goods.setSaleRetailPrice(goodsProduct.getSaleRetailPrice());

        GoodsBaseData goodsBaseData = goodsManager.getGoodsBase(goods);
        map.put("goodsBase", goodsBaseData);

        SkuInfo skuInfo = getSkuInfo(cart, goods);
        map.put("skuInfo", skuInfo);

        map.put("totalPrice", getPriceBySku(skuInfo));
        map.put("saleUserId", cart.getSaleUserId());
        map.put("cartId", cart.getId());
        return map;
    }

    private BigDecimal getPriceBySku(SkuInfo skuInfo) {
        BigDecimal totalPrice = BigDecimal.ZERO;

        SelectedSpecInfo selectedGoodsSpec = skuInfo.getSelectedGoodsSpec();
        if (null != selectedGoodsSpec) {
            BigDecimal price=BigDecimal.ZERO;
            if(ObjectUtil.isNotNull(skuInfo.getSelectedSkuVipSale())&&skuInfo.getSelectedSkuVipSale().getPrice()!=null){
                price=skuInfo.getSelectedSkuVipSale().getPrice();
            }
            else{
                price=selectedGoodsSpec.getPrice();
            }
            totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(selectedGoodsSpec.getStock())));
        }

        List<SelectedSpecInfo> selectedCustomSpecList = skuInfo.getSelectedCustomSpec();
        if (CollectionUtils.isNotEmpty(selectedCustomSpecList)) {
            for (SelectedSpecInfo selectedSpecInfo : selectedCustomSpecList) {
                totalPrice = totalPrice.add(selectedSpecInfo.getPrice().multiply(BigDecimal.valueOf(selectedSpecInfo.getStock())));
            }
        }

        List<SelectedSpecInfo> selectedServiceSpecList = skuInfo.getSelectedServiceSpec();
        if (CollectionUtils.isNotEmpty(selectedServiceSpecList)) {
            for (SelectedSpecInfo selectedSpecInfo : selectedServiceSpecList) {
                totalPrice = totalPrice.add(selectedSpecInfo.getPrice().multiply(BigDecimal.valueOf(selectedSpecInfo.getStock())));
            }
        }

        List<SelectedSpecInfo> selectedExtendSpecList = skuInfo.getSelectedExtendSpec();
        if (CollectionUtils.isNotEmpty(selectedExtendSpecList)) {
            for (SelectedSpecInfo selectedSpecInfo : selectedExtendSpecList) {
                totalPrice = totalPrice.add(selectedSpecInfo.getPrice().multiply(BigDecimal.valueOf(selectedSpecInfo.getStock())));
            }
        }
        return totalPrice;
    }

    public GoodsVipSalesDto getSelectProductVipSale(String vipJson, Integer userLevel, Integer number,Integer vipPriceFlag){
        GoodsVipSalesDto goodsVipSalesDto=null;
        if(vipPriceFlag!=null&&vipPriceFlag==1){
            LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(userLevel);
            AgedmallVipLevelExample vipLevelExample=new AgedmallVipLevelExample();
            vipLevelExample.setOrderByClause("vip_level DESC");
            vipLevelExample.createCriteria().andDeletedEqualTo(false).andUseFlagEqualTo(1).andVipLevelLessThanOrEqualTo(litemallUser.getUserLevel().intValue());
            List<AgedmallVipLevel> agedmallVipLevelList = agedmallVipLevelMapper.selectByExample(vipLevelExample);
            List<GoodsVipSalesDto> productVipSales = goodsManager.getProductVipSales(vipJson);
            for (int i = 0; i < productVipSales.size(); i++) {
                for (int j = 0; j < agedmallVipLevelList.size(); j++) {
                    if(productVipSales.get(i).getLevel().equals(agedmallVipLevelList.get(j).getVipLevel())&&productVipSales.get(i).getLimit()<=number){
                            goodsVipSalesDto=productVipSales.get(i);
                    }
                }
            }
        }

        return goodsVipSalesDto;
    }

    private SkuInfo getSkuInfo (LitemallCart cart, StoreGoodsVo goods) {
        SkuInfo skuInfo = new SkuInfo();
        GoodsSku goodsSku = goodsManager.getSkuItemList(goods);
        skuInfo.setGoodsSku(goodsSku);

        boolean flag = GoodsConstant.GOODS_TYPE_LEASE.equals(goods.getGoodsType());
//        LitemallGoodsProduct goodsProduct = productService.findById(cart.getProductId());
        StoreGoodsProductVo goodsProduct = agedmallStoreGoodsService.getStoreGoodsProduct(goods.getStoreId(), goods.getId(), cart.getProductId());
        if (flag) {

                AgedmallChargeTemplateLeasePeriod agedmallChargeTemplateLeasePeriod;
                if(null != cart.getRuleId()){
                    agedmallChargeTemplateLeasePeriod = agedmallChargeTemplateLeasePeriodMapper.selectByPrimaryKeySelective(cart.getRuleId());

                }
                else{
                    AgedmallChargeTemplateLeasePeriodExample leasePeriodExample=new AgedmallChargeTemplateLeasePeriodExample();
                    leasePeriodExample.setOrderByClause("id ASC");
                    leasePeriodExample.createCriteria().andDeletedEqualTo(false).andCustomTemplateIdEqualTo(goods.getLeaseChargeTemolateId());
                    agedmallChargeTemplateLeasePeriod = agedmallChargeTemplateLeasePeriodMapper.selectOneByExample(leasePeriodExample);
                }
                goodsProduct.setSaleRetailPrice(agedmallChargeTemplateLeasePeriod.getBasePrice());

        }


            SelectedSpecInfo selectedGoodsSpec = new SelectedSpecInfo();
            selectedGoodsSpec.setId(cart.getProductId());
            selectedGoodsSpec.setStock(cart.getNumber().intValue());
            selectedGoodsSpec.setPrice(flag ? goodsProduct.getLeaseDeposit() : goodsProduct.getSaleRetailPrice());
            skuInfo.setSelectedGoodsSpec(selectedGoodsSpec);
            GoodsVipSalesDto selectProductVipSale = getSelectProductVipSale(goodsProduct.getVipJson(),
                    cart.getUserId(),cart.getNumber().intValue(),goods.getVipPriceFlag());
            skuInfo.setSelectedSkuVipSale(selectProductVipSale);



        List<SelectedSpecInfo> selectedCustomSpecList = new ArrayList<>();
        List<CustomSpecInfo> customSpec = JSON.parseArray(cart.getPartIds(), CustomSpecInfo.class);
        if (CollectionUtils.isNotEmpty(customSpec)) {
            for (CustomSpecInfo customSpecInfo : customSpec) {
                List<CustomSpecSelectedInfo> selectedList = customSpecInfo.getSelected();
                if (CollectionUtils.isNotEmpty(selectedList)) {
                    for (CustomSpecSelectedInfo customSpecSelectedInfo : selectedList) {
//                        LitemallGoodsProduct product = productService.findById(Integer.parseInt(customSpecSelectedInfo.getSkuId()));
                        StoreGoodsVo storeGoodsVo =agedmallStoreGoodsService.getStoreGoodsById(customSpecSelectedInfo.getId());
                        StoreGoodsProductVo goodsProductVo = agedmallStoreGoodsService.getStoreGoodsProduct(storeGoodsVo.getStoreId(), storeGoodsVo.getId(), Integer.parseInt(customSpecSelectedInfo.getSkuId()));
                        SelectedSpecInfo selectedSpecInfo = new SelectedSpecInfo();
                        selectedSpecInfo.setId(customSpecSelectedInfo.getId());
                        selectedSpecInfo.setSkuId(Integer.parseInt(customSpecSelectedInfo.getSkuId()));
                        selectedSpecInfo.setStock(goodsProductVo.getPartsNumber() == 1 ? 1 : cart.getNumber().intValue());
                        selectedSpecInfo.setPrice(goodsProductVo.getSaleRetailPrice());
                        selectedCustomSpecList.add(selectedSpecInfo);
                    }
                }
            }
        }
        skuInfo.setSelectedCustomSpec(selectedCustomSpecList);

        List<SelectedSpecInfo> selectedServiceSpecList = new ArrayList<>();
        List<CustomSpecInfo> serviceSpec = JSON.parseArray(cart.getOnlineServiceIds(), CustomSpecInfo.class);
        if (CollectionUtils.isNotEmpty(serviceSpec)) {
            for (CustomSpecInfo customSpecInfo : serviceSpec) {
                List<CustomSpecSelectedInfo> selectedList = customSpecInfo.getSelected();
                if (CollectionUtils.isNotEmpty(selectedList)) {
                    for (CustomSpecSelectedInfo customSpecSelectedInfo : selectedList) {
                        AgedmallOnlineService onlineService = agedmallOnlinesService.queryAgedmallOnLineId(customSpecSelectedInfo.getId());
                        String city = LocationContext.get().getCity();
                        ServiceProductVo product = litemallGoodsProductService.findServiceById(Integer.parseInt(customSpecSelectedInfo.getSkuId()), city);
                        SelectedSpecInfo selectedSpecInfo = new SelectedSpecInfo();
                        selectedSpecInfo.setId(customSpecSelectedInfo.getId());
                        selectedSpecInfo.setSkuId(Integer.parseInt(customSpecSelectedInfo.getSkuId()));
                        selectedSpecInfo.setPrice(null == product ? onlineService.getCostPrice() : product.getCityProductPrice());
                        selectedSpecInfo.setStock(1);
                        selectedServiceSpecList.add(selectedSpecInfo);
                    }
                }
            }
        }
        skuInfo.setSelectedServiceSpec(selectedServiceSpecList);

        List<SelectedSpecInfo> selectedExtendSpecList = new ArrayList<>();
        List<ExtendSpecInfo> extendSpec = JSON.parseArray(cart.getServiceIds(), ExtendSpecInfo.class);
        if (CollectionUtils.isNotEmpty(extendSpec)) {
            for (ExtendSpecInfo extendSpecInfo : extendSpec) {
                List<String> selectedList = Arrays.asList(extendSpecInfo.getSelected().split(","));
                if (CollectionUtils.isNotEmpty(selectedList)) {
                    for (String s : selectedList) {
                        LitemallGoodsProduct product = productService.findById(Integer.parseInt(s));
                        SelectedSpecInfo selectedSpecInfo = new SelectedSpecInfo();
                        selectedSpecInfo.setId(Integer.parseInt(s));
                        selectedSpecInfo.setStock(product.getPartsNumber() == 1 ? 1 : cart.getNumber().intValue());
                        selectedSpecInfo.setPrice(product.getPrice());
                        selectedExtendSpecList.add(selectedSpecInfo);
                    }
                }
            }
        }
        skuInfo.setSelectedExtendSpec(selectedExtendSpecList);
        return skuInfo;
    }

    private SelectGoodsSkuInfo getSelectGoodsSku(LitemallCart cart) {
        SelectGoodsSkuInfo selectGoodsSkuInfo = new SelectGoodsSkuInfo();

        GoodsSpecInfo goodsSpec = new GoodsSpecInfo();
        goodsSpec.setId(cart.getGoodsId());
        goodsSpec.setSkuId(cart.getProductId() + "");
        goodsSpec.setStock(cart.getNumber().intValue());
        goodsSpec.setCartId(cart.getId());
        selectGoodsSkuInfo.setGoodsSpec(goodsSpec);

        List<CustomSpecInfo> customSpec = JSON.parseArray(cart.getPartIds(), CustomSpecInfo.class);
        selectGoodsSkuInfo.setCustomSpec(customSpec);

        List<ExtendSpecInfo> extendSpec = JSON.parseArray(cart.getServiceIds(), ExtendSpecInfo.class);
        selectGoodsSkuInfo.setExtendSpec(extendSpec);
        return selectGoodsSkuInfo;
    }

    public BaseResult recommendList(Integer page, Integer limit) {
        Location location = LocationContext.get();
        List<StoreGoodsVo> goodsList = goodsService.queryCartRecommendList(location.getProvince(), location.getCity(), page, limit);
        List<GoodsBaseData> dataList = goodsList.stream().map(goodsManager::getGoodsBase).collect(Collectors.toList());
        int total = goodsService.countCartRecommendList(location.getProvince(), location.getCity());

        PageData<GoodsBaseData> pageData = new PageData<>();
        int pages = total % limit == 0 ? total / limit : total / limit + 1;
        pageData.setNowPage(page);
        pageData.setTotalPage(pages);
        pageData.setTotalRows(total);
        pageData.setRows(dataList);
//        return RespUtil.success(pageData);
        // 先不返购物车推荐列表
        return RespUtil.success();
    }

    public BaseResult updateCartStock(Integer userId, Integer cartId, Integer stock) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        LitemallCart litemallCart = cartService.findById(cartId);
        if (null == litemallCart || !userId.equals(litemallCart.getUserId())) {
            return RespUtil.badArgumentValue();
        }
//        LitemallGoodsProduct product = productService.findById(litemallCart.getProductId());
        StoreGoodsVo goodsVo = agedmallStoreGoodsService.getStoreGoodsById(litemallCart.getGoodsId());
        int stockNum = orderManager.getByStoreGoods(goodsVo, litemallCart.getProductId());
        if (stock > stockNum) {
            throw new BizException("库存不足");
        }
        litemallCart.setNumber(stock.shortValue());
        cartService.updateById(litemallCart);
        return RespUtil.success();
    }

    public BaseResult createOrder(Integer userId, Integer addressId, String groupIds, Integer isHospitalUrgent, Integer hosId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        LitemallAddress litemallAddress = addressService.query(userId, addressId);
        if (null == litemallAddress) {
            return RespUtil.badArgumentValue();
        }
        List<LitemallCart> cartList = cartService.getByGoodsGroupIdList(userId, Arrays.asList(groupIds.split(",")));
        if (CollectionUtils.isEmpty(cartList)) {
            return RespUtil.badArgumentValue();
        }
        List<Integer> goodsIdList = cartList.stream().map(LitemallCart::getGoodsId).distinct().collect(Collectors.toList());
        List<StoreGoodsVo> goodsList = goodsService.queryByIdList(goodsIdList);
        List<String> cityList = goodsList.stream().filter(p -> GoodsConstant.GOODS_TYPE_LEASE.equals(p.getGoodsType()))
                .map(StoreGoodsVo::getCityName).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(cityList) && cityList.size() > 1) {
            throw new BizException("存在非同城租赁商品");
        }
        Map<Integer, StoreGoodsVo> goodsMap = goodsList.stream().collect(Collectors.toMap(StoreGoodsVo::getStoreGoodsId, p -> p));

        // 每个租赁商品都是一个子订单，售卖商品同一个店铺的N个售卖商品为一个子订单
        List<List<LitemallCart>> orderCartList = new ArrayList<>();
        // 临时存放 门店id，购物车
        Map<Integer, List<LitemallCart>> storeMap= new HashMap<>();
        for (LitemallCart litemallCart : cartList) {
            StoreGoodsVo goods = goodsMap.get(litemallCart.getGoodsId());
            if (GoodsConstant.GOODS_TYPE_LEASE.equals(goods.getGoodsType())) {
                List<LitemallCart> carts = new ArrayList<>();
                carts.add(litemallCart);
                orderCartList.add(carts);
            }
            if (GoodsConstant.GOODS_TYPE_SALE.equals(goods.getGoodsType())) {
                if (storeMap.containsKey(goods.getStoreId())) {
                    List<LitemallCart> carts = storeMap.get(goods.getStoreId());
                    carts.add(litemallCart);
                } else {
                    List<LitemallCart> carts = new ArrayList<>();
                    carts.add(litemallCart);
                    storeMap.put(goods.getStoreId(), carts);
                }
            }
        }

        for (List<LitemallCart> value : storeMap.values()) {
            orderCartList.add(value);
        }

        Map<String, Object> data = new HashMap<>();
        // 临时子订单列表
        List<Map<String, Object>> tempSubOrderList = new ArrayList();
        // 临时服务订单列表
        List<Map<String, Object>> tempServiceOrderList = new ArrayList();
        // 失效商品列表
        List<SubOrderGoodsVo> invalidGoodsList = new ArrayList<>();
        // 是否小时达
        AgedmallHospitalSend hospitalSend = null;
        if (isHospitalUrgent.equals(1) && null != hosId) {
            hospitalSend = agedmallHospitalSendService.getById(hosId);
        }
        // 是否含有租赁可使用抵扣金商品
        boolean hasDeductionGoods = false;
        // 服务商品编号
        int serviceGoodsNo = 0;


        for (List<LitemallCart> carts : orderCartList) {
            //商品规格列表
            List<Integer> productList=carts.parallelStream().map(LitemallCart::getProductId).collect(Collectors.toList());
            List<StoreGoodsProductVo> storeGoodsProductVoList = agedmallStoreGoodsService.getStoreGoodsProductListByProductIds(productList);

            Map<String, Object> tempSubOrderMap = new HashMap<>();
            // storeInfo
            StoreGoodsVo goods = goodsMap.get(carts.get(0).getGoodsId());
            AgedmallStore store = agedmallStoreService.findStoreById(goods.getStoreId());
            Map<String, Object> map = new HashMap<>();
            map.put("id", store.getId());
            map.put("name", store.getStoreName());
            map.put("logo", store.getLogo());
            map.put("isSelf", store.getOwnOptFlg());
            tempSubOrderMap.put("storeInfo", map);
            // goodsList
            List<SubOrderGoodsVo> subOrderGoodsVos = new ArrayList<>();
            List<StoreGoodsVo> storeGoodsVoList = new ArrayList<>();
            BigDecimal orderPrice = BigDecimal.ZERO;
            for (LitemallCart cart : carts) {
                serviceGoodsNo++;
                StoreGoodsVo litemallGoods = goodsMap.get(cart.getGoodsId());
                StoreGoodsProductVo goodsProduct = agedmallStoreGoodsService.getStoreGoodsProduct(litemallGoods.getStoreId(), litemallGoods.getId(), cart.getProductId());
                litemallGoods.setSaleRetailPrice(goodsProduct.getSaleRetailPrice());

                boolean flag = GoodsConstant.GOODS_TYPE_LEASE.equals(litemallGoods.getGoodsType());
                SubOrderGoodsVo subOrderGoodsVo = new SubOrderGoodsVo();
                subOrderGoodsVo.setServiceGoodsNo(serviceGoodsNo);
                if (StringUtils.isNotEmpty(cart.getSaleUserId())) {
                    subOrderGoodsVo.setSaleUserId(Integer.parseInt(cart.getSaleUserId()));
                }
                GoodsBaseData goodsBaseData = goodsManager.getGoodsBase(litemallGoods);
                subOrderGoodsVo.setGoodsBase(goodsBaseData);

                BigDecimal totalPrice = BigDecimal.ZERO;

                SkuInfo skuInfo = new SkuInfo();
                GoodsSku goodsSku = goodsManager.getSkuItemList(litemallGoods);
                skuInfo.setGoodsSku(goodsSku);

                    SelectedSpecInfo selectedGoodsSpec = new SelectedSpecInfo();
                    selectedGoodsSpec.setId(cart.getProductId());
                    selectedGoodsSpec.setStock(cart.getNumber().intValue());
                    skuInfo.setSelectedGoodsSpec(selectedGoodsSpec);
                    GoodsVipSalesDto selectProductVipSale = getSelectProductVipSale(goodsProduct.getVipJson(),
                            cart.getUserId(),cart.getNumber().intValue(),litemallGoods.getVipPriceFlag());
                    skuInfo.setSelectedSkuVipSale(selectProductVipSale);


                BigDecimal salePrice=ObjectUtil.isNotNull(selectProductVipSale)?selectProductVipSale.getPrice():goodsProduct.getSaleRetailPrice();
                totalPrice = totalPrice.add(new BigDecimal(cart.getNumber()).multiply(flag ? goodsProduct.getLeaseDeposit() : salePrice ));

                // 必须配件 是否有库存
                boolean neededParts = true;
                // 必须配件 是否支持小时达医院
                boolean neededHosp = true;
                List<SelectedSpecInfo> selectedCustomSpecList = new ArrayList<>();
                List<CustomSpecInfo> customSpecInfos = JSONObject.parseArray(cart.getPartIds(), CustomSpecInfo.class);
                if (CollectionUtils.isNotEmpty(customSpecInfos)) {
                    for (CustomSpecInfo customSpecInfo : customSpecInfos) {
                        AgedmallGoodsSpecificationInfo specificationInfo = agedmallGoodsSpecificationInfoService.getById(customSpecInfo.getId());
                        // 是否必选
                        boolean mustSelect = null != specificationInfo && specificationInfo.getMinSelCount() >= 1;
                        List<CustomSpecSelectedInfo> selected = customSpecInfo.getSelected();
                        for (CustomSpecSelectedInfo customSpecSelectedInfo : selected) {
//                            LitemallGoodsProduct product = productService.findById(Integer.parseInt(customSpecSelectedInfo.getSkuId()));
                            StoreGoodsVo storeGoodsVo =agedmallStoreGoodsService.getStoreGoodsById(customSpecSelectedInfo.getId());
                            StoreGoodsProductVo goodsProductVo = agedmallStoreGoodsService.getStoreGoodsProduct(litemallGoods.getStoreId(), storeGoodsVo.getId(), Integer.parseInt(customSpecSelectedInfo.getSkuId()));

                            SelectedSpecInfo selectedSpecInfo = new SelectedSpecInfo();
                            selectedSpecInfo.setId(customSpecSelectedInfo.getId());
                            selectedSpecInfo.setSkuId(Integer.parseInt(customSpecSelectedInfo.getSkuId()));
                            selectedSpecInfo.setStock(goodsProductVo.getPartsNumber() == 1 ? 1 : cart.getNumber().intValue());

                            // 查询库存和库存类型
                            StockTypeDto stockTypeDto = orderManager.getStockTypeByStoreGoods(storeGoodsVo, Integer.parseInt(customSpecSelectedInfo.getSkuId()),
                                    litemallAddress.getLng(), litemallAddress.getLat());
                            if (mustSelect && null == stockTypeDto) {
                                neededParts = false;
                            }
                            if (null != stockTypeDto) {
                                selectedSpecInfo.setIsInvalid(0);
                            } else {
                                selectedSpecInfo.setIsInvalid(1);
                            }

                            // 查询医院小时达
                            if (null != hospitalSend) {
                                List<String> storeIds = Arrays.asList(hospitalSend.getStoreIds().split(","));
                                int type = hospitalSend.getGoodsType();
                                List<String> goodsIds = Arrays.asList(org.apache.commons.lang3.StringUtils.split(hospitalSend.getGoodsIds(), ","));
                                boolean supportHosp = storeIds.contains(storeGoodsVo.getStoreId()+"") && (type == 1 || goodsIds.contains(storeGoodsVo.getId()+""));
                                if (mustSelect && !supportHosp) {
                                    neededHosp = false;
                                }
                                if (!supportHosp) {
                                    selectedSpecInfo.setIsInvalid(1);
                                }
                            }

                            selectedCustomSpecList.add(selectedSpecInfo);

                            AgedmallGoodsParts parts = agedmallGoodsPartsService.getByGoodsIdAndCustGoodsId(litemallGoods.getId(), storeGoodsVo.getId());
                            // 售卖商品 或是先付的租赁商品 订单价格加上配件价格
                            if (GoodsConstant.GOODS_TYPE_SALE.equals(litemallGoods.getGoodsType())
                                    || (null != parts && parts.getPayOrder().equals(0))) {
                                totalPrice = totalPrice.add(new BigDecimal(selectedSpecInfo.getStock()).multiply(goodsProductVo.getSaleRetailPrice()));
                            }
                        }
                    }
                }
                skuInfo.setSelectedCustomSpec(selectedCustomSpecList);

                // 特色服务
                List<SelectedSpecInfo> selectedExtendSpecList = new ArrayList<>();
                List<ExtendSpecInfo> extendSpecInfos = JSONObject.parseArray(cart.getServiceIds(), ExtendSpecInfo.class);
                if (CollectionUtils.isNotEmpty(extendSpecInfos)) {
                    for (ExtendSpecInfo extendSpecInfo : extendSpecInfos) {
                        String[] selectedArr = extendSpecInfo.getSelected().split(",");
                        for (String s : selectedArr) {
                            LitemallGoodsProduct product = productService.findById(Integer.parseInt(s));
                            SelectedSpecInfo selectedSpecInfo = new SelectedSpecInfo();
                            selectedSpecInfo.setId(Integer.parseInt(s));
                            selectedSpecInfo.setStock(product.getPartsNumber() == 1 ? 1 : cart.getNumber().intValue());
                            selectedExtendSpecList.add(selectedSpecInfo);
                            totalPrice = totalPrice.add(new BigDecimal(selectedSpecInfo.getStock()).multiply(product.getPrice()));
                        }
                    }
                }
                skuInfo.setSelectedExtendSpec(selectedExtendSpecList);
                subOrderGoodsVo.setSkuInfo(skuInfo);
                subOrderGoodsVo.setTotalPrice(totalPrice.doubleValue());
                subOrderGoodsVo.setGoodsLease(new GoodsLease(litemallGoods.getCreditLease(), WxPayScoreConfig.MIN_SCORE));

                // 商品是否有效
                if (goodsBaseData.getIsOffline() == 1) {
                    invalidGoodsList.add(subOrderGoodsVo);
                    continue;
                }
                // 必须配件是否有库存
                if (!neededParts) {
                    invalidGoodsList.add(subOrderGoodsVo);
                    continue;
                }
                // 必须配件是否支持医院小时达
                if (!neededHosp) {
                    invalidGoodsList.add(subOrderGoodsVo);
                    continue;
                }
                // 查询医院小时达
                if (null != hospitalSend) {
                    List<String> storeIds = Arrays.asList(hospitalSend.getStoreIds().split(","));
                    int type = hospitalSend.getGoodsType();
                    List<String> goodsIds = Arrays.asList(org.apache.commons.lang3.StringUtils.split(hospitalSend.getGoodsIds(), ","));
                    boolean supportHosp = storeIds.contains(litemallGoods.getStoreId()+"") && (type == 1 || goodsIds.contains(litemallGoods.getId()+""));
                    if (!supportHosp) {
                        invalidGoodsList.add(subOrderGoodsVo);
                        continue;
                    }
                }

                StoreGoodsVo storeGoodsVo = goodsMap.get(cart.getGoodsId());
                storeGoodsVo.setStock(cart.getNumber().intValue());
                StockTypeDto stockTypeDto = orderManager.getStockTypeByStoreGoods(storeGoodsVo, cart.getProductId(),
                        litemallAddress.getLng(), litemallAddress.getLat());
                // 没有库存
                if (null == stockTypeDto) {
                    invalidGoodsList.add(subOrderGoodsVo);
                    continue;
                }
                subOrderGoodsVo.setStockType(stockTypeDto.getStockType());
                subOrderGoodsVo.setCloudStockId(stockTypeDto.getCloudStockId());
                storeGoodsVo.setStockType(stockTypeDto.getStockType());
                storeGoodsVo.setCloudStockId(stockTypeDto.getCloudStockId());

                // 超出范围
                boolean isDelivery = orderManager.isDelivery(storeGoodsVo, litemallAddress, InventoryUtil.STOCK_CLOUD.equals(stockTypeDto.getStockType()),stockTypeDto.getCloudStockId());
                if (isDelivery) {
                    invalidGoodsList.add(subOrderGoodsVo);
                    continue;

                }

                // 在线服务,,,在线服务要放在商品库存和配送范围判断之后，因为没有商品 服务也就不能下单了
                List<CustomSpecInfo> serviceSpecInfos = JSONObject.parseArray(cart.getOnlineServiceIds(), CustomSpecInfo.class);
                if (CollectionUtils.isNotEmpty(serviceSpecInfos)) {
                    for (CustomSpecInfo serviceSpecInfo : serviceSpecInfos) {
                        List<CustomSpecSelectedInfo> selected = serviceSpecInfo.getSelected();
                        for (CustomSpecSelectedInfo serviceSpecSelectedInfo : selected) {
                            JSONObject tempServiceOrder = new JSONObject();

                            AgedmallOnlineService onlineService = agedmallOnlinesService.queryAgedmallOnLineId(serviceSpecSelectedInfo.getId());
                            String city = litemallAddress.getCity();
                            ServiceProductVo product = litemallGoodsProductService.findServiceById(Integer.parseInt(serviceSpecSelectedInfo.getSkuId()), city);

                            SubOrderGoodsVo serviceInfo = new SubOrderGoodsVo();
                            serviceInfo.setServiceGoodsNo(serviceGoodsNo);
                            GoodsBaseData serviceBaseData = goodsManager.getServiceBaseData(onlineService, product);
                            serviceInfo.setGoodsBase(serviceBaseData);

                            SkuInfo serviceSkuInfo = new SkuInfo();
                            GoodsSku serviceSku = goodsManager.getServiceSku(onlineService);
                            serviceSkuInfo.setGoodsSku(serviceSku);

                            SelectedSpecInfo selectedServiceSpec = new SelectedSpecInfo();
                            selectedServiceSpec.setId(Integer.parseInt(serviceSpecSelectedInfo.getSkuId()));
                            // 服务默认1次
                            selectedServiceSpec.setStock(1);
                            serviceSkuInfo.setSelectedGoodsSpec(selectedServiceSpec);

                            serviceInfo.setSkuInfo(serviceSkuInfo);
                            serviceInfo.setGoodsId(litemallGoods.getId());
                            serviceInfo.setStoreGoodsId(litemallGoods.getStoreGoodsId());

                            // 服务不支持当前城市
                            if (null == product.getCityProductPrice()) {
                                invalidGoodsList.add(serviceInfo);
                                continue;
                            }

                            tempServiceOrder.put("goodsInfo", serviceInfo);
                            tempServiceOrder.put("extends", goodsManager.getServiceExtends(onlineService, litemallAddress.getCity()));
//                            BigDecimal price = null != product.getCityProductPrice() ? product.getCityProductPrice() : product.getPrice();
                            tempServiceOrder.put("totalPrice", product.getCityProductPrice());

                            AgedmallGoodsOnlineServiceExample goodsOnlineServiceExample = new AgedmallGoodsOnlineServiceExample();
                            goodsOnlineServiceExample.or().andDeletedEqualTo(false)
                                    .andGoodsIdEqualTo(litemallGoods.getId())
                                    .andOnlineSerivceProductIdEqualTo(onlineService.getId());
                            AgedmallGoodsOnlineService goodsOnlineService = agedmallGoodsOnlineServiceMapper.selectOneByExample(goodsOnlineServiceExample);
                            tempServiceOrder.put("isPrepaid", GoodsConstant.GOODS_TYPE_LEASE.equals(litemallGoods.getGoodsType()) ? goodsOnlineService.getPayOrder() : 0);

                            tempServiceOrderList.add(tempServiceOrder);
                        }
                    }
                }

                subOrderGoodsVos.add(subOrderGoodsVo);
                orderPrice = orderPrice.add(totalPrice);
                storeGoodsVoList.add(storeGoodsVo);

                // 判断是否有抵扣金
                if (goodsBaseData.getDeductNum() > 0) {
                    hasDeductionGoods = true;
                }
            }
            tempSubOrderMap.put("goodsList", subOrderGoodsVos);

            if (CollectionUtils.isNotEmpty(storeGoodsVoList)) {
                Integer channel=0;
                String hosLinkCode=null;
                List<ChannelGoodsBindDto> bindDtoList=new ArrayList<>();
                if(isHospitalUrgent==1){
                    List<Integer> channelList=carts.stream().map(LitemallCart::getChannel).distinct().sorted().collect(Collectors.toList());
                    carts.forEach( cart ->{
                        ChannelGoodsBindDto goodsBindDto=new ChannelGoodsBindDto();
                        goodsBindDto.setHosLinkCode(cart.getHosLinkCode());
                        goodsBindDto.setGoodsId(cart.getGoodsId().longValue());
                        goodsBindDto.setChannel(cart.getChannel());
                        goodsBindDto.setSaleUserId(Integer.parseInt(cart.getSaleUserId()));
                        bindDtoList.add(goodsBindDto);
                    });
                    //判断特殊情况，如果存在医院推广并且是售卖商品，配送方式和正常一样
                    if(channelList.contains(1)&&storeGoodsVoList.get(0).getGoodsType().equals("sale")){
                        channel=0;
                    }
                    //判断特殊情况，如果存在医院推广并且是租赁商品，配送方式为channel=1
                    else if(channelList.contains(1)&&storeGoodsVoList.get(0).getGoodsType().equals("lease")){
                        channel=1;
                    }
                    //其余的为正常情况
                    else{
                        channel=channelList.get(0);
                    }
                }
                // extends
                Map<String, Object> extendsMap = orderManager.getExtends(storeGoodsVoList, litemallAddress, hospitalSend,channel,hosLinkCode,storeGoodsProductVoList);
                extendsMap.put("province", store.getProvinceName());
                extendsMap.put("city", store.getCityName());
                tempSubOrderMap.put("extends", extendsMap);
                tempSubOrderMap.put("channelGoodsBind", bindDtoList);

                // 单个租赁商品 运费是先付还是后付
                if (1 == storeGoodsVoList.size()) {
                    StoreGoodsVo storeGoods = storeGoodsVoList.get(0);
                    if (GoodsConstant.GOODS_TYPE_LEASE.equals(storeGoods.getGoodsType())) {
                        tempSubOrderMap.put("isPrepaid", storeGoods.getPayOrder());
                    }
                }
                // totalPrice
                tempSubOrderMap.put("totalPrice", orderPrice);

                // 是医院小时达 还是预约小时达，列表中有一个是预约小时达，就算预约小时达
                LitemallCart cart = carts.stream().filter(p -> null != p.getIsSub() && p.getIsSub().equals(1)).findFirst().orElse(null);
                int isSub = null == cart ? 0 : 1;
                tempSubOrderMap.put("isSub", isSub);

                tempSubOrderList.add(tempSubOrderMap);
            }
        }
        data.put("tempSubOrderList", tempSubOrderList);
        data.put("tempServiceOrderList", tempServiceOrderList);
        data.put("invalidGoodsList", invalidGoodsList);

        // 订单说明信息
        List<ExplainDto> explainDtos = goodsList.stream()
                .map(p -> new ExplainDto(GoodsConstant.GOODS_TYPE_SALE.equals(p.getGoodsType()) ? 1 : 0, p.getStoreId())).distinct().collect(Collectors.toList());
        data.put("readmeList", orderManager.getReadmeList(explainDtos));
        // 信用租最大金额
        data.put("creditLeaseMaxPrice", new BigDecimal(SystemConfig.getLitemallCreditLeaseMaxPrice()));
        // 是否可使用抵扣金(有抵扣金，且有租赁商品可使用抵扣金)
        AgedmallUserInfo agedmallUserInfo = agedmallUserInfoService.getByUid(userId);
        int canUseDeduct = (agedmallUserInfo.getDeductAmount().compareTo(BigDecimal.ZERO) > 0 && hasDeductionGoods) ? 1 : 0;
        data.put("canUseDeduct", canUseDeduct);
        return RespUtil.success(data);
    }


    public BaseResult getHospitalList(Integer userId, String groupIds) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        List<LitemallCart> cartList = cartService.getByGoodsGroupIdList(userId, Arrays.asList(groupIds.split(",")));
        if (CollectionUtils.isEmpty(cartList)) {
            return RespUtil.badArgumentValue();
        }
        List<Integer> goodsIdList = cartList.stream().map(LitemallCart::getGoodsId).distinct().collect(Collectors.toList());
        List<StoreGoodsVo> goodsList = goodsService.queryByIdList(goodsIdList);
        List<AgedmallHospitalSend> agedmallHospitalSends = new ArrayList<>();
        for (StoreGoodsVo storeGoodsVo : goodsList) {
            List<AgedmallHospitalSend> hospitalSends = agedmallHospitalSendService.getByStoreAndGoods(storeGoodsVo.getStoreId(), storeGoodsVo.getId());
            agedmallHospitalSends.addAll(hospitalSends);
        }

        List<GoodsHospitalInfo> hospitalInfos = agedmallHospitalSends.stream().distinct().map(GoodsHospitalInfo::new).collect(Collectors.toList());

        return RespUtil.success(hospitalInfos);
    }

    @Transactional
    public BaseResult saveOrderToCart(Integer userId, String bigOrderCode, String childOrderCode) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        LitemallOrder order = orderService.findBySn(userId, bigOrderCode);
        if (null == order) {
            return RespUtil.badArgumentValue();
        }
        LitemallOrderItem subOrder = orderService.findItemBySn(userId, bigOrderCode, childOrderCode);
        if (null == subOrder) {
            return RespUtil.badArgumentValue();
        }
        // 子订单所有商品
        List<LitemallOrderGoods> list = orderGoodsService.getOrderGoodsListByChildOrderCode(childOrderCode);
        // 商品列表
        List<LitemallOrderGoods> orderGoodsList = list.stream().filter(p -> OrderGoodsConstant.TYPE_GOODS.endsWith(p.getType())).collect(Collectors.toList());
        // 配件列表
        List<LitemallOrderGoods> partsList = list.stream().filter(p -> OrderGoodsConstant.TYPE_CUSTOM.endsWith(p.getType())).collect(Collectors.toList());
        Map<Integer, List<LitemallOrderGoods>> partsMap = partsList.stream().collect(Collectors.toMap(
                LitemallOrderGoods::getPartentId,
                p -> {
                    List<LitemallOrderGoods> carts = new ArrayList<>();
                    carts.add(p);
                    return carts;
                },
                (list1, list2) -> {
                    list1.addAll(list2);
                    return list1;
                }
        ));
        // 服务列表
        List<LitemallOrderGoods> serviceList = list.stream().filter(p -> OrderGoodsConstant.TYPE_EXTEND.endsWith(p.getType())).collect(Collectors.toList());
        Map<Integer, List<LitemallOrderGoods>> serviceMap = serviceList.stream().collect(Collectors.toMap(
                LitemallOrderGoods::getPartentId,
                p -> {
                    List<LitemallOrderGoods> carts = new ArrayList<>();
                    carts.add(p);
                    return carts;
                },
                (list1, list2) -> {
                    list1.addAll(list2);
                    return list1;
                }
        ));

        orderGoodsList.forEach(p -> {
            List<LitemallOrderGoods> parts = partsMap.containsKey(p.getId()) ? partsMap.get(p.getId()) : new ArrayList<>();
            List<LitemallOrderGoods> services = serviceMap.containsKey(p.getId()) ? serviceMap.get(p.getId()) : new ArrayList<>();
            Map<Integer, List<CustomSpecSelectedInfo>> pMap = parts.stream().collect(Collectors.toMap(
                    LitemallOrderGoods::getSpecInfoId,
                    o -> {
                        List<CustomSpecSelectedInfo> infos = new ArrayList<>();
                        infos.add(new CustomSpecSelectedInfo(o.getStoreGoodsId(), o.getProductId()+""));
                        return infos;
                    },
                    (p1, p2) -> {
                        p1.addAll(p2);
                        return p1;
                    }
            ));
            Map<Integer, String> sMap = services.stream().collect(Collectors.toMap(
                    LitemallOrderGoods::getSpecInfoId,
                    o -> o.getProductId() + "",
                    (p1, p2) -> {
                        p1 = p1 + "," +p2;
                        return p1;
                    }
            ));
            List<CustomSpecInfo> customSpec = pMap.entrySet().stream()
                    .map(q -> new CustomSpecInfo(q.getKey(), q.getValue())
                    ).collect(Collectors.toList());
            List<ExtendSpecInfo> extendSpec = sMap.entrySet().stream()
                    .map(s -> new ExtendSpecInfo(s.getKey(), s.getValue())
                    ).collect(Collectors.toList());

            GoodsSpecInfo goodsSpec = new GoodsSpecInfo();
            goodsSpec.setId(p.getStoreGoodsId());
            goodsSpec.setSkuId(p.getProductId() + "");
            goodsSpec.setStock(p.getNumber().intValue());
            SelectGoodsSkuInfo mainGoods = new SelectGoodsSkuInfo();
            mainGoods.setGoodsSpec(goodsSpec);
            mainGoods.setCustomSpec(customSpec);
            mainGoods.setExtendSpec(extendSpec);
            AddGoodsForm addGoodsForm = new AddGoodsForm();
            addGoodsForm.setMainGoods(mainGoods);

            addGoods(userId, addGoodsForm);
        });

        return RespUtil.success();
    }
}
